/**
 * H5页面构建器主类
 * 整合所有功能模块，提供统一的API接口
 */
class PageBuilder {
    constructor() {
        this.canvas = document.getElementById('canvas');
        this.propertiesPanel = document.getElementById('propertiesContent');
        this.elementManager = null;
        this.dragDropManager = null;
        this.structureManager = null;
        this.accordionManager = null;
        this.apiManager = null;
        
        // Swiper实例
        this.canvasSwiper = null;
        
        // 多页面管理
        this.pages = [
            {
                id: 'page_1',
                name: '页面 1',
                background: { color: '#ffffff', image: '' },
                elements: []
            }
        ];
        this.currentPageIndex = 0;
        this.pageSettings = {
            infiniteScroll: false,
            transitionEffect: 'slide', // slide, fade, none
            pageSwitchMode: 'both' // click, swipe, both
        };
        
        this.init();
    }

    /**
     * 初始化应用
     */
    init() {
        // 检查必要的DOM元素是否存在
        if (!this.canvas) {
            console.error('Canvas element not found');
            return;
        }
        
        if (!this.propertiesPanel) {
            console.error('Properties panel not found');
            return;
        }

        // 初始化各个模块
        this.elementManager = new ElementManager(this.canvas, this.propertiesPanel);
        this.dragDropManager = new DragDropManager(this.canvas, this.elementManager);
        this.structureManager = new StructureManager(this.elementManager);
        this.accordionManager = new AccordionManager();
        this.apiManager = new ApiManager();

        // 设置画布点击事件
        this.setupCanvasEvents();
        
        // 设置工具栏事件
        this.setupToolbarEvents();
        
        // 设置背景设置事件
        this.setupBackgroundEvents();
        
        // 设置加载模态框事件
        this.setupLoadModalEvents();

        // 初始化画布提示文案显示状态
        this.elementManager.updateCanvasPlaceholder();
        
        // 初始化Swiper
        this.initCanvasSwiper();

        console.log('H5页面构建器初始化完成');
    }
    
    /**
     * 初始化画布Swiper
     */
    initCanvasSwiper() {
        const self = this;
        this.canvasSwiper = new Swiper('.canvasSwiper', {
            direction: 'vertical',
            allowTouchMove: false,  // 禁用手动滑动，只允许按钮控制
            loop: false,
            speed: 600,
            effect: this.pageSettings.transitionEffect === 'fade' ? 'fade' : 'slide',
            on: {
                slideChange: function() {
                    const realIndex = this.realIndex;
                    console.log('Swiper slideChange event:', {
                        realIndex: realIndex,
                        currentPageIndex: self.currentPageIndex,
                        totalSlides: this.slides ? this.slides.length : 0
                    });
                    
                    if (realIndex !== self.currentPageIndex) {
                        self.currentPageIndex = realIndex;
                        self.onSwiperPageChange(realIndex);
                    } else {
                        // 即使索引相同，也要确保UI更新
                        self.updatePageNavigation();
                    }
                }
            }
        });
        
        console.log('Canvas Swiper initialized (touch disabled, button control only)', {
            totalSlides: this.canvasSwiper.slides ? this.canvasSwiper.slides.length : 0
        });
    }
    
    /**
     * Swiper页面切换回调
     */
    onSwiperPageChange(pageIndex) {
        // 保存之前页面的数据（但不重新渲染）
        const previousIndex = this.currentPageIndex;
        if (previousIndex >= 0 && previousIndex < this.pages.length && previousIndex !== pageIndex) {
            this.saveCurrentPageData();
        }
        
        // 更新当前页面索引
        this.currentPageIndex = pageIndex;
        
        // 加载新页面数据
        const page = this.pages[pageIndex];
        if (page) {
            // 找到正确的画布元素 - 使用更精确的选择器，只选择.canvas元素
            const canvas = document.querySelector(`.canvas[data-page="${pageIndex}"]`);
            console.log('Looking for canvas with selector:', `.canvas[data-page="${pageIndex}"]`, 'found:', canvas);
            
            if (canvas) {
                this.canvas = canvas;
                this.elementManager.canvas = canvas;
            } else {
                console.error('Canvas not found for page:', pageIndex);
            }
            
            // 更新背景
            this.background = page.background || { color: '#ffffff', image: '' };
            this.updateCanvasBackground();
            
            // 加载元素
            this.elementManager.setCurrentPage(pageIndex);
            this.elementManager.loadPageElements(page.elements || []);
        }
        
        // 更新UI
        this.updatePageTabs();
        this.updatePageNavigation();
        
        // 更新画布提示文案
        this.elementManager.updateCanvasPlaceholder();
        
        // 重新触发当前页面的所有动画
        this.triggerPageAnimations(pageIndex);
        
        console.log(`Swiper switched to page ${pageIndex + 1}`);
    }

    /**
     * 触发页面动画
     * @param {number} pageIndex - 页面索引
     */
    triggerPageAnimations(pageIndex) {
        console.log('触发页面动画 - 页面索引:', pageIndex);
        
        const canvas = document.querySelector(`.canvas[data-page="${pageIndex}"]`);
        if (!canvas) {
            console.warn('Canvas not found for animation trigger:', pageIndex);
            return;
        }
        
        // 获取当前页面的所有元素
        const page = this.pages[pageIndex];
        if (!page || !page.elements) {
            console.log('页面或元素不存在:', { page, elements: page?.elements });
            return;
        }
        
        console.log('页面元素数量:', page.elements.length);
        
        // 为每个有动画的元素重新触发动画
        page.elements.forEach((element, index) => {
            console.log(`检查元素 ${index + 1}:`, {
                id: element.id,
                type: element.type,
                hasStyle: !!element.style,
                animationName: element.style?.animationName
            });
            
            if (element.style && element.style.animationName && element.style.animationName !== 'none') {
                const elementDiv = document.getElementById(element.id);
                console.log('找到DOM元素:', elementDiv);
                
                if (elementDiv) {
                    // 移除所有动画相关的类
                    const classesToRemove = Array.from(elementDiv.classList).filter(cls => 
                        cls.startsWith('animate__') || cls.startsWith('animate-')
                    );
                    console.log('要移除的动画类:', classesToRemove);
                    classesToRemove.forEach(cls => elementDiv.classList.remove(cls));
                    
                    // 使用 requestAnimationFrame 确保DOM更新后再添加动画
                    requestAnimationFrame(() => {
                        // 重新添加动画类
                        elementDiv.classList.add('animate__animated');
                        elementDiv.classList.add(`animate__${element.style.animationName}`);
                        
                        // 设置动画参数
                        if (element.style.animationDuration) {
                            elementDiv.style.setProperty('--animate-duration', element.style.animationDuration);
                        }
                        if (element.style.animationDelay) {
                            elementDiv.style.setProperty('--animate-delay', element.style.animationDelay);
                        }
                        if (element.style.animationFillMode) {
                            elementDiv.style.animationFillMode = element.style.animationFillMode;
                        }
                        
                        // 处理动画次数
                        if (element.style.animationIterationCount === 'infinite') {
                            elementDiv.classList.add('animate__infinite');
                        } else if (element.style.animationIterationCount && element.style.animationIterationCount !== '1') {
                            elementDiv.classList.add(`animate__repeat-${element.style.animationIterationCount}`);
                        }
                        
                        console.log(`重新触发元素 ${element.id} 的动画: ${element.style.animationName}`);
                    });
                } else {
                    console.warn('找不到DOM元素:', element.id);
                }
            }
        });
    }

    /**
     * 设置画布事件
     */
    setupCanvasEvents() {
        if (!this.canvas || !this.elementManager) {
            console.warn('Canvas or element manager not available');
            return;
        }
        
        this.canvas.addEventListener('click', (e) => {
            // 如果点击的是画布本身或占位符，取消选择
            if (e.target === this.canvas || e.target.classList.contains('canvas-placeholder')) {
                this.elementManager.selectElement(null);
            }
        });
    }

    /**
     * 设置工具栏事件
     */
    setupToolbarEvents() {
        // 清空画布
        const clearBtn = document.getElementById('clearCanvas');
        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                this.clearCanvas();
            });
        }

        // 保存页面
        const saveBtn = document.getElementById('saveBtn');
        if (saveBtn) {
            saveBtn.addEventListener('click', () => {
                this.savePage();
            });
        }

        // 加载页面
        const loadBtn = document.getElementById('loadBtn');
        if (loadBtn) {
            loadBtn.addEventListener('click', () => {
                this.showLoadModal();
            });
        }

        // 生成预览
        const previewBtn = document.getElementById('previewBtn');
        console.log('previewBtn found:', previewBtn);
        if (previewBtn) {
            previewBtn.addEventListener('click', () => {
                console.log('previewBtn clicked');
                this.generatePreview();
            });
        } else {
            console.error('previewBtn not found');
        }

        // 多页面管理事件
        this.setupPageManagementEvents();
    }

    /**
     * 设置背景设置事件
     */
    setupBackgroundEvents() {
        const backgroundBtn = document.getElementById('backgroundBtn');
        const backgroundModal = document.getElementById('backgroundModal');
        const closeBackgroundModal = document.querySelector('#backgroundModal .close');
        const applyBackground = document.getElementById('applyBackground');

        if (backgroundBtn) {
            backgroundBtn.addEventListener('click', () => {
                this.showBackgroundModal();
            });
        }

        if (closeBackgroundModal) {
            closeBackgroundModal.addEventListener('click', () => {
                backgroundModal.style.display = 'none';
            });
        }

        if (applyBackground) {
            applyBackground.addEventListener('click', () => {
                this.applyBackground();
            });
        }

        // 背景颜色选择器色值回显
        const bgColorInput = document.getElementById('bgColor');
        const bgColorValue = document.getElementById('bgColorValue');
        if (bgColorInput && bgColorValue) {
            bgColorInput.addEventListener('input', (e) => {
                bgColorValue.textContent = e.target.value;
            });
            bgColorInput.addEventListener('change', (e) => {
                bgColorValue.textContent = e.target.value;
            });
        }
    }

    showBackgroundModal() {
        const bgColorInput = document.getElementById('bgColor');
        const bgColorValue = document.getElementById('bgColorValue');
        const bgImageInput = document.getElementById('bgImage');
        
        bgColorInput.value = this.background.color;
        bgColorValue.textContent = this.background.color;
        bgImageInput.value = this.background.image || '';
        document.getElementById('backgroundModal').style.display = 'block';
    }

    /**
     * 设置加载模态框事件
     */
    setupLoadModalEvents() {
        const loadModal = document.getElementById('loadModal');
        const closeLoadModal = document.querySelector('#loadModal .close');
        const loadPageBtn = document.getElementById('confirmLoad');

        if (closeLoadModal) {
            closeLoadModal.addEventListener('click', () => {
                loadModal.style.display = 'none';
            });
        }

        if (loadPageBtn) {
            loadPageBtn.addEventListener('click', () => {
                this.loadPage();
            });
        }

        // 保存模态框事件
        const confirmSaveBtn = document.getElementById('confirmSave');
        if (confirmSaveBtn) {
            confirmSaveBtn.addEventListener('click', () => {
                this._confirmSave();
            });
        }

        // 保存模态框关闭按钮
        const saveModalClose = document.querySelector('#saveModal .close');
        if (saveModalClose) {
            saveModalClose.addEventListener('click', () => {
                document.getElementById('saveModal').style.display = 'none';
            });
        }

        // 点击保存模态框外部关闭
        const saveModal = document.getElementById('saveModal');
        if (saveModal) {
            saveModal.addEventListener('click', (e) => {
                if (e.target === saveModal) {
                    saveModal.style.display = 'none';
                }
            });
        }

        // 用户下拉菜单功能
        const userDropdownToggle = document.getElementById('userDropdownToggle');
        const userDropdownMenu = document.getElementById('userDropdownMenu');
        const userDropdown = document.querySelector('.user-dropdown');
        
        if (userDropdownToggle && userDropdownMenu) {
            // 切换下拉菜单显示/隐藏
            userDropdownToggle.addEventListener('click', (e) => {
                e.stopPropagation();
                userDropdown.classList.toggle('active');
            });
            
            // 点击外部关闭下拉菜单
            document.addEventListener('click', (e) => {
                if (!userDropdown.contains(e.target)) {
                    userDropdown.classList.remove('active');
                }
            });
        }

        // 用户中心功能
        const userCenterBtn = document.getElementById('userCenterBtn');
        if (userCenterBtn) {
            userCenterBtn.addEventListener('click', (e) => {
                e.preventDefault();
                userDropdown.classList.remove('active');
                window.toast.show('用户中心功能开发中...', 'info');
            });
        }

        // 用户管理功能
        const userManageBtn = document.getElementById('userManageBtn');
        if (userManageBtn) {
            userManageBtn.addEventListener('click', (e) => {
                e.preventDefault();
                userDropdown.classList.remove('active');
                this.showUserManageModal();
            });
        }

        // 退出登录功能
        const logoutBtn = document.getElementById('logoutBtn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', (e) => {
                e.preventDefault();
                userDropdown.classList.remove('active');
                window.toast.confirm('确定要退出登录吗？', () => {
                    localStorage.removeItem('isLoggedIn');
                    localStorage.removeItem('username');
                    window.location.href = '/login.html';
                }, () => {
                    // 取消退出，不做任何操作
                });
            });
        }

        // 更新欢迎文本和权限控制
        this.updateUserInfo();
    }

    /**
     * 清空画布
     */
    clearCanvas() {
        window.toast.confirm('确定要清空画布吗？\n此操作将清空画布上的所有元素，且无法撤销', () => {
            this._confirmClearCanvas();
        }, () => {
            // 取消清空，不做任何操作
        });
    }

    _confirmClearCanvas() {
        this.elementManager.clearElements();
        this.background = { color: '#ffffff', image: '' };
        this.canvas.style.backgroundColor = this.background.color;
        this.canvas.style.backgroundImage = 'none';
        this.canvas.style.backgroundSize = 'initial';
        this.canvas.style.backgroundPosition = 'initial';
        this.canvas.style.backgroundRepeat = 'initial';
        window.toast.success('画布已清空');
    }

    /**
     * 更新用户信息和权限控制
     */
    updateUserInfo() {
        const currentUser = window.userManager.getCurrentUser();
        const welcomeText = document.getElementById('welcomeText');
        const userManageBtn = document.getElementById('userManageBtn');
        
        if (currentUser) {
            // 更新欢迎文本
            if (welcomeText) {
                welcomeText.textContent = `欢迎，${currentUser.displayName || currentUser.username}`;
            }
            
            // 根据权限显示/隐藏用户管理菜单
            if (userManageBtn) {
                if (window.userManager.isSuperAdmin()) {
                    userManageBtn.style.display = 'flex';
                } else {
                    userManageBtn.style.display = 'none';
                }
            }
        }
    }

    /**
     * 显示用户管理模态框
     */
    async showUserManageModal() {
        const modal = document.getElementById('userManageModal');
        if (modal) {
            modal.style.display = 'block';
            await this.loadUserList();
            this.setupUserManageEvents();
        }
    }

    /**
     * 加载用户列表
     */
    async loadUserList() {
        const userList = document.getElementById('userList');
        if (!userList) return;

        try {
            const users = await window.userManager.getAllUsers();
            this.renderUserList(users);
        } catch (error) {
            console.error('加载用户列表失败:', error);
            window.toast.error('加载用户列表失败');
        }
    }

    /**
     * 渲染用户列表
     */
    renderUserList(users) {
        const userList = document.getElementById('userList');
        if (!userList) return;

        userList.innerHTML = users.map(user => `
            <div class="user-item" data-user-id="${user.id}">
                <div class="user-info">
                    <div class="user-avatar">${user.displayName ? user.displayName.charAt(0).toUpperCase() : user.username.charAt(0).toUpperCase()}</div>
                    <div class="user-details">
                        <h4>${user.displayName || user.username}</h4>
                        <p>@${user.username} • ${user.role === 'super_admin' ? '超级管理员' : '普通用户'}</p>
                    </div>
                    <div class="user-role ${user.role}">${user.role === 'super_admin' ? '超级管理员' : '普通用户'}</div>
                </div>
                <div class="user-actions">
                    <button class="edit-user-btn" data-user-id="${user.id}">编辑</button>
                    <button class="delete-user-btn" data-user-id="${user.id}" ${user.username === 'admin' ? 'disabled' : ''}>删除</button>
                </div>
            </div>
        `).join('');
    }

    /**
     * 设置用户管理事件
     */
    setupUserManageEvents() {
        // 添加用户按钮
        const addUserBtn = document.getElementById('addUserBtn');
        if (addUserBtn) {
            addUserBtn.onclick = () => this.showUserEditModal();
        }

        // 搜索功能
        const searchInput = document.getElementById('userSearchInput');
        if (searchInput) {
            searchInput.oninput = (e) => this.filterUsers(e.target.value);
        }

        // 编辑用户按钮
        document.querySelectorAll('.edit-user-btn').forEach(btn => {
            btn.onclick = (e) => {
                const userId = parseInt(e.target.dataset.userId);
                this.showUserEditModal(userId);
            };
        });

        // 删除用户按钮
        document.querySelectorAll('.delete-user-btn').forEach(btn => {
            btn.onclick = (e) => {
                const userId = parseInt(e.target.dataset.userId);
                this.deleteUser(userId);
            };
        });

        // 模态框关闭
        const modal = document.getElementById('userManageModal');
        const closeBtn = modal.querySelector('.close');
        if (closeBtn) {
            closeBtn.onclick = () => modal.style.display = 'none';
        }
        modal.onclick = (e) => {
            if (e.target === modal) modal.style.display = 'none';
        };
    }

    /**
     * 过滤用户
     */
    filterUsers(searchTerm) {
        const userItems = document.querySelectorAll('.user-item');
        userItems.forEach(item => {
            const username = item.querySelector('h4').textContent.toLowerCase();
            const displayName = item.querySelector('p').textContent.toLowerCase();
            const matches = username.includes(searchTerm.toLowerCase()) || displayName.includes(searchTerm.toLowerCase());
            item.style.display = matches ? 'flex' : 'none';
        });
    }

    /**
     * 显示用户编辑模态框
     */
    async showUserEditModal(userId = null) {
        const modal = document.getElementById('userEditModal');
        const title = document.getElementById('userEditTitle');
        const form = document.getElementById('userEditForm');
        
        if (userId) {
            // 编辑模式
            title.textContent = '编辑用户';
            const users = await window.userManager.getAllUsers();
            const user = users.find(u => u.id === userId);
            if (user) {
                document.getElementById('editUsername').value = user.username;
                document.getElementById('editPassword').value = '';
                document.getElementById('editPassword').placeholder = '留空表示不修改密码';
                document.getElementById('editDisplayName').value = user.displayName || '';
                document.getElementById('editRole').value = user.role;
            }
        } else {
            // 添加模式
            title.textContent = '添加用户';
            form.reset();
            document.getElementById('editPassword').placeholder = '请输入密码';
        }

        modal.style.display = 'block';
        this.setupUserEditEvents(userId);
    }

    /**
     * 设置用户编辑事件
     */
    setupUserEditEvents(userId) {
        const form = document.getElementById('userEditForm');
        const modal = document.getElementById('userEditModal');
        const cancelBtn = document.getElementById('cancelUserEdit');

        form.onsubmit = async (e) => {
            e.preventDefault();
            await this.saveUser(userId);
        };

        cancelBtn.onclick = () => modal.style.display = 'none';

        // 模态框关闭
        const closeBtn = modal.querySelector('.close');
        if (closeBtn) {
            closeBtn.onclick = () => modal.style.display = 'none';
        }
        modal.onclick = (e) => {
            if (e.target === modal) modal.style.display = 'none';
        };
    }

    /**
     * 保存用户
     */
    async saveUser(userId) {
        const username = document.getElementById('editUsername').value;
        const password = document.getElementById('editPassword').value;
        const displayName = document.getElementById('editDisplayName').value;
        const role = document.getElementById('editRole').value;

        if (!username) {
            window.toast.error('用户名不能为空');
            return;
        }

        if (!userId && !password) {
            window.toast.error('密码不能为空');
            return;
        }

        try {
            const userData = { username, displayName, role };
            if (password) userData.password = password;

            let result;
            if (userId) {
                result = await window.userManager.updateUser(userId, userData);
            } else {
                result = await window.userManager.addUser(userData);
            }

            if (result.success) {
                window.toast.success(userId ? '用户更新成功' : '用户添加成功');
                document.getElementById('userEditModal').style.display = 'none';
                await this.loadUserList();
            } else {
                window.toast.error(result.message);
            }
        } catch (error) {
            console.error('保存用户失败:', error);
            window.toast.error('保存用户失败');
        }
    }

    /**
     * 删除用户
     */
    async deleteUser(userId) {
        window.toast.confirm('确定要删除这个用户吗？', async () => {
            try {
                const result = await window.userManager.deleteUser(userId);
                if (result.success) {
                    window.toast.success('用户删除成功');
                    await this.loadUserList();
                } else {
                    window.toast.error(result.message);
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                window.toast.error('删除用户失败');
            }
        });
    }

    /**
     * 保存页面
     */
    async savePage() {
        document.getElementById('saveFilename').value = '';
        document.getElementById('saveModal').style.display = 'block';
    }

    async _confirmSave() {
        const filename = document.getElementById('saveFilename').value.trim();
        if (!filename) {
            window.toast.error('请输入文件名');
            return;
        }

        // 保存当前页面数据
        this.saveCurrentPageData();

        const pageData = {
            pages: this.pages,
            pageSettings: this.pageSettings,
            currentPageIndex: this.currentPageIndex
        };

        try {
            const response = await fetch('/api/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ pageData, filename })
            });

            const result = await response.json();
            if (result.success) {
                window.toast.success('保存成功！');
                document.getElementById('saveModal').style.display = 'none';
            } else {
                window.toast.error('保存失败：' + result.message);
            }
        } catch (error) {
            window.toast.error('保存失败：' + error.message);
        }
    }

    /**
     * 显示加载模态框
     */
    async showLoadModal() {
        try {
            const response = await fetch('/api/pages');
            const result = await response.json();
            
            const select = document.getElementById('loadFileSelect');
            select.innerHTML = '<option value="">请选择文件</option>';
            
            if (result.success && result.data.length > 0) {
                result.data.forEach(page => {
                    const option = document.createElement('option');
                    option.value = page.filename;
                    option.textContent = page.name;
                    select.appendChild(option);
                });
            }
            
            document.getElementById('loadModal').style.display = 'block';
        } catch (error) {
            window.toast.error('获取文件列表失败：' + error.message);
        }
    }

    /**
     * 加载页面
     */
    async loadPage() {
        const filename = document.getElementById('loadFileSelect').value;
        if (!filename) {
            window.toast.error('请选择要读取的文件');
            return;
        }

        try {
            const response = await fetch(`/api/load/${filename}`);
            const result = await response.json();
            
            if (result.success) {
                this.loadPageData(result.data);
                window.toast.success('读取成功！');
                document.getElementById('loadModal').style.display = 'none';
            } else {
                window.toast.error('读取失败：' + result.message);
            }
        } catch (error) {
            window.toast.error('读取失败：' + error.message);
        }
    }

    /**
     * 加载页面数据到画布
     * @param {Object} pageData - 页面数据
     */
    loadPageData(pageData) {
        // 检查是否是多页面数据
        if (pageData.pages && Array.isArray(pageData.pages)) {
            // 多页面数据
            this.pages = pageData.pages;
            this.pageSettings = pageData.pageSettings || {
                infiniteScroll: false,
                transitionEffect: 'slide',
                pageSwitchMode: 'click'
            };
            this.currentPageIndex = pageData.currentPageIndex || 0;
            
            // 切换到第一个页面
            this.switchToPage(this.currentPageIndex);
            
            // 更新UI
            this.updatePageTabs();
            this.updatePageNavigation();
        } else {
            // 单页面数据（兼容旧版本）
            this.pages = [{
                id: 'page_1',
                name: '页面 1',
                background: pageData.background || { color: '#ffffff', image: '' },
                elements: pageData.elements || []
            }];
            this.currentPageIndex = 0;
            this.pageSettings = {
                infiniteScroll: false,
                transitionEffect: 'slide',
                pageSwitchMode: 'click'
            };
            
            this.switchToPage(0);
            this.updatePageTabs();
            this.updatePageNavigation();
        }
        
        // 更新画布提示文案显示状态
        this.elementManager.updateCanvasPlaceholder();
    }

    /**
     * 设置多页面管理事件
     */
    setupPageManagementEvents() {
        // 添加页面按钮
        const addPageBtn = document.getElementById('addPageBtn');
        if (addPageBtn) {
            addPageBtn.addEventListener('click', () => {
                this.addPage();
            });
        }

        // 页面设置按钮
        const pageSettingsBtn = document.getElementById('pageSettingsBtn');
        if (pageSettingsBtn) {
            pageSettingsBtn.addEventListener('click', () => {
                this.showPageSettingsModal();
            });
        }

        // 翻页按钮
        const prevPageBtn = document.getElementById('prevPageBtn');
        const nextPageBtn = document.getElementById('nextPageBtn');
        
        if (prevPageBtn) {
            prevPageBtn.addEventListener('click', () => {
                this.switchToPage(this.currentPageIndex - 1);
            });
        }
        
        if (nextPageBtn) {
            nextPageBtn.addEventListener('click', () => {
                this.switchToPage(this.currentPageIndex + 1);
            });
        }

        // 页面设置模态框事件
        this.setupPageSettingsModalEvents();
    }

    /**
     * 设置页面设置模态框事件
     */
    setupPageSettingsModalEvents() {
        const modal = document.getElementById('pageSettingsModal');
        const closeBtn = document.getElementById('pageSettingsClose');
        const saveBtn = document.getElementById('pageSettingsSave');
        const cancelBtn = document.getElementById('pageSettingsCancel');

        if (closeBtn) {
            closeBtn.addEventListener('click', () => {
                this.hidePageSettingsModal();
            });
        }

        if (cancelBtn) {
            cancelBtn.addEventListener('click', () => {
                this.hidePageSettingsModal();
            });
        }

        if (saveBtn) {
            saveBtn.addEventListener('click', () => {
                this.savePageSettings();
            });
        }

        // 点击模态框外部关闭
        if (modal) {
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    this.hidePageSettingsModal();
                }
            });
        }
    }

    /**
     * 添加新页面
     */
    addPage() {
        // 先保存当前页面数据
        this.saveCurrentPageData();
        
        const newPageId = `page_${Date.now()}`;
        const newPage = {
            id: newPageId,
            name: `页面 ${this.pages.length + 1}`,
            background: { color: '#ffffff', image: '' },
            elements: [] // 新页面有独立的空元素数组
        };
        
        this.pages.push(newPage);
        
        console.log('Adding new page:', {
            newPageName: newPage.name,
            newPageIndex: this.pages.length - 1,
            totalPages: this.pages.length
        });
        
        // 添加新的Swiper slide
        const newPageIndex = this.pages.length - 1;
        const slideHTML = `
            <div class="swiper-slide">
                <div class="canvas" data-page="${newPageIndex}">
                    <div class="canvas-placeholder">
                        <p>拖拽左侧元素到此处开始设计</p>
                    </div>
                </div>
            </div>
        `;
        
        if (this.canvasSwiper) {
            this.canvasSwiper.appendSlide(slideHTML);
            console.log('Swiper slide appended, total slides:', this.canvasSwiper.slides.length);
        }
        
        this.updatePageTabs();
        
        // 强制更新一次页面导航（在切换之前）
        this.updatePageNavigation();
        
        this.switchToPage(this.pages.length - 1);
        
        window.toast.success(`已添加新页面：${newPage.name}`);
    }

    /**
     * 删除页面
     * @param {number} pageIndex - 页面索引
     */
    deletePage(pageIndex) {
        if (this.pages.length <= 1) {
            window.toast.warning('至少需要保留一个页面');
            return;
        }

        const page = this.pages[pageIndex];
        if (confirm(`确定要删除页面"${page.name}"吗？`)) {
            this.pages.splice(pageIndex, 1);
            
            // 如果删除的是当前页面，切换到前一个页面
            if (pageIndex === this.currentPageIndex) {
                this.currentPageIndex = Math.max(0, this.currentPageIndex - 1);
            } else if (pageIndex < this.currentPageIndex) {
                this.currentPageIndex--;
            }
            
            this.updatePageTabs();
            this.switchToPage(this.currentPageIndex);
            
            window.toast.success(`已删除页面：${page.name}`);
        }
    }

    /**
     * 切换到指定页面
     * @param {number} pageIndex - 页面索引
     */
    switchToPage(pageIndex) {
        if (pageIndex < 0 || pageIndex >= this.pages.length) {
            return;
        }

        // 保存当前页面数据
        this.saveCurrentPageData();

        // 使用Swiper切换页面
        if (this.canvasSwiper && this.canvasSwiper.activeIndex !== pageIndex) {
            this.canvasSwiper.slideTo(pageIndex, 600);
        }

        // 切换到新页面
        this.currentPageIndex = pageIndex;
        const page = this.pages[pageIndex];
        
        // 获取正确的画布元素 - 使用更精确的选择器
        const canvas = document.querySelector(`.canvas[data-page="${pageIndex}"]`);
        console.log('switchToPage: Looking for canvas:', `.canvas[data-page="${pageIndex}"]`, 'found:', canvas);
        
        if (canvas) {
            this.canvas = canvas;
            this.elementManager.canvas = canvas;
        } else {
            console.error('switchToPage: Canvas not found for page:', pageIndex);
        }
        
        // 更新ElementManager
        this.elementManager.setCurrentPage(pageIndex);
        this.elementManager.loadPageElements(page.elements || []);
        
        // 更新背景
        this.background = page.background || { color: '#ffffff', image: '' };
        this.updateCanvasBackground();
        
        // 更新UI
        this.updatePageTabs();
        this.updatePageNavigation();
        
        // 更新画布提示文案
        this.elementManager.updateCanvasPlaceholder();
        
        console.log(`切换到页面 ${pageIndex + 1}，元素数量: ${page.elements ? page.elements.length : 0}`);
    }

    /**
     * 保存当前页面数据
     */
    saveCurrentPageData() {
        if (this.pages[this.currentPageIndex]) {
            // 保存当前页面的元素数据
            const currentElements = this.elementManager.getCurrentPageElements();
            this.pages[this.currentPageIndex].elements = [...currentElements];
            this.pages[this.currentPageIndex].background = { ...this.background };
            
            console.log(`保存页面 ${this.currentPageIndex + 1} 数据:`, {
                elementsCount: this.pages[this.currentPageIndex].elements.length,
                elements: this.pages[this.currentPageIndex].elements,
                background: this.pages[this.currentPageIndex].background
            });
        } else {
            console.warn('saveCurrentPageData: Current page not found!', {
                currentPageIndex: this.currentPageIndex,
                totalPages: this.pages.length
            });
        }
    }

    /**
     * 更新页面标签
     */
    updatePageTabs() {
        const pageTabs = document.getElementById('pageTabs');
        if (!pageTabs) return;

        pageTabs.innerHTML = '';
        
        this.pages.forEach((page, index) => {
            const tab = document.createElement('div');
            tab.className = `page-tab ${index === this.currentPageIndex ? 'active' : ''}`;
            tab.setAttribute('data-page', index);
            
            tab.innerHTML = `
                <span>${page.name}</span>
                <button class="page-close" data-page="${index}">×</button>
            `;
            
            // 点击切换页面
            tab.addEventListener('click', (e) => {
                if (!e.target.classList.contains('page-close')) {
                    this.switchToPage(index);
                }
            });
            
            // 删除页面
            const closeBtn = tab.querySelector('.page-close');
            closeBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                this.deletePage(index);
            });
            
            pageTabs.appendChild(tab);
        });
    }

    /**
     * 更新页面导航
     */
    updatePageNavigation() {
        const prevBtn = document.getElementById('prevPageBtn');
        const nextBtn = document.getElementById('nextPageBtn');
        const indicator = document.getElementById('pageIndicator');
        
        console.log('updatePageNavigation called:', {
            currentPageIndex: this.currentPageIndex,
            totalPages: this.pages.length,
            indicator: indicator,
            prevBtn: prevBtn,
            nextBtn: nextBtn
        });
        
        if (prevBtn) {
            const shouldDisablePrev = this.currentPageIndex === 0 && !this.pageSettings.infiniteScroll;
            prevBtn.disabled = shouldDisablePrev;
            console.log('Prev button:', {
                currentPageIndex: this.currentPageIndex,
                infiniteScroll: this.pageSettings.infiniteScroll,
                shouldDisable: shouldDisablePrev,
                disabled: prevBtn.disabled
            });
        }
        
        if (nextBtn) {
            const shouldDisableNext = this.currentPageIndex === this.pages.length - 1 && !this.pageSettings.infiniteScroll;
            nextBtn.disabled = shouldDisableNext;
            console.log('Next button:', {
                currentPageIndex: this.currentPageIndex,
                totalPages: this.pages.length,
                isLastPage: this.currentPageIndex === this.pages.length - 1,
                infiniteScroll: this.pageSettings.infiniteScroll,
                shouldDisable: shouldDisableNext,
                disabled: nextBtn.disabled
            });
        }
        
        if (indicator) {
            const newText = `${this.currentPageIndex + 1} / ${this.pages.length}`;
            indicator.textContent = newText;
            console.log('Updated indicator text to:', newText);
        } else {
            console.warn('Page indicator element not found!');
        }
    }

    /**
     * 显示页面设置模态框
     */
    showPageSettingsModal() {
        const modal = document.getElementById('pageSettingsModal');
        if (modal) {
            // 设置当前值
            document.getElementById('transitionEffect').value = this.pageSettings.transitionEffect;
            document.getElementById('infiniteScroll').checked = this.pageSettings.infiniteScroll;
            document.getElementById('pageSwitchMode').value = this.pageSettings.pageSwitchMode || 'click';
            
            modal.style.display = 'flex';
        }
    }

    /**
     * 隐藏页面设置模态框
     */
    hidePageSettingsModal() {
        const modal = document.getElementById('pageSettingsModal');
        if (modal) {
            modal.style.display = 'none';
        }
    }

    /**
     * 保存页面设置
     */
    savePageSettings() {
        this.pageSettings.transitionEffect = document.getElementById('transitionEffect').value;
        this.pageSettings.infiniteScroll = document.getElementById('infiniteScroll').checked;
        this.pageSettings.pageSwitchMode = document.getElementById('pageSwitchMode').value;
        
        this.hidePageSettingsModal();
        this.updatePageNavigation();
        
        window.toast.success('页面设置已保存');
    }

    /**
     * 更新画布背景
     */
    updateCanvasBackground() {
        // 确保background对象存在
        if (!this.background) {
            this.background = { color: '#ffffff', image: '' };
        }
        
        this.canvas.style.backgroundColor = this.background.color || '#ffffff';
        if (this.background.image) {
            this.canvas.style.backgroundImage = `url(${this.background.image})`;
            this.canvas.style.backgroundSize = 'cover';
            this.canvas.style.backgroundPosition = 'center';
            this.canvas.style.backgroundRepeat = 'no-repeat';
        } else {
            this.canvas.style.backgroundImage = 'none';
            this.canvas.style.backgroundSize = 'initial';
            this.canvas.style.backgroundPosition = 'initial';
            this.canvas.style.backgroundRepeat = 'initial';
        }
    }

    /**
     * 生成预览
     */
    async generatePreview() {
        console.log('generatePreview called');
        console.log('elementManager:', this.elementManager);
        console.log('elements length:', this.elementManager ? this.elementManager.getElements().length : 'elementManager is null');
        
        // 保存当前页面数据
        this.saveCurrentPageData();
        
        // 检查是否有页面和元素
        const hasElements = this.pages.some(page => page.elements && page.elements.length > 0);
        if (!hasElements) {
            window.toast.warning('请先添加一些元素');
            return;
        }

        // 创建输入对话框
        console.log('Creating input toast...');
        const inputToast = window.toast.show('请输入预览文件名', 'info', 0);
        console.log('Toast created:', inputToast);
        console.log('Toast parent:', inputToast.parentNode);
        console.log('Toast in DOM:', document.body.contains(inputToast));
        
        inputToast.innerHTML = `
            <div style="display: flex; flex-direction: column; gap: 12px; width: 100%;">
                <div style="display: flex; align-items: center; gap: 8px;">
                    <span style="font-size: 16px;">📄</span>
                    <span style="font-weight: 600; color: #2c5282;">预览设置</span>
                </div>
                <div style="color: #4a5568; font-size: 13px; line-height: 1.4;">
                    请输入预览文件名，系统将生成对应的HTML页面
                </div>
                <div style="display: flex; flex-direction: column; gap: 10px;">
                    <input type="text" id="previewFilename" value="preview_${Date.now()}" 
                           style="padding: 8px 12px; border: 1px solid #cbd5e0; border-radius: 6px; font-size: 13px; width: 100%; box-sizing: border-box; background: #f7fafc; color: #2d3748; outline: none; transition: border-color 0.2s;">
                    <div style="display: flex; gap: 8px; justify-content: flex-end;">
                        <button id="cancel-preview" 
                                style="background: #a0aec0; color: white; border: none; padding: 6px 16px; border-radius: 6px; cursor: pointer; font-size: 12px; transition: background-color 0.2s;">
                            取消
                        </button>
                        <button id="confirm-preview" 
                                style="background: #4299e1; color: white; border: none; padding: 6px 16px; border-radius: 6px; cursor: pointer; font-size: 12px; transition: background-color 0.2s;">
                            生成预览
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        console.log('Toast innerHTML set');
        console.log('Toast computed style:', window.getComputedStyle(inputToast));
        console.log('Toast position:', inputToast.style.position);
        console.log('Toast z-index:', inputToast.style.zIndex);
        console.log('Toast display:', window.getComputedStyle(inputToast).display);
        console.log('Toast visibility:', window.getComputedStyle(inputToast).visibility);
        console.log('Toast opacity:', window.getComputedStyle(inputToast).opacity);
        console.log('Toast transform:', window.getComputedStyle(inputToast).transform);
        console.log('Toast container display:', window.getComputedStyle(inputToast.parentNode).display);
        console.log('Toast classes:', inputToast.className);
        console.log('Toast has show class:', inputToast.classList.contains('show'));
        console.log('Toast has hide class:', inputToast.classList.contains('hide'));

        // 绑定事件
        const confirmBtn = inputToast.querySelector('#confirm-preview');
        const cancelBtn = inputToast.querySelector('#cancel-preview');
        console.log('Confirm button found:', confirmBtn);
        console.log('Cancel button found:', cancelBtn);
        
        if (confirmBtn) {
            confirmBtn.addEventListener('click', () => {
                console.log('Confirm button clicked');
                this._confirmPreview();
                inputToast.remove();
            });
        }
        
        if (cancelBtn) {
            cancelBtn.addEventListener('click', () => {
                console.log('Cancel button clicked');
                inputToast.remove();
            });
        }
    }

    async _confirmPreview() {
        const filename = document.getElementById('previewFilename').value.trim();
        if (!filename) {
            window.toast.error('请输入文件名');
            return;
        }

        const pageData = {
            pages: this.pages,
            pageSettings: this.pageSettings,
            currentPageIndex: this.currentPageIndex
        };

        try {
            const response = await fetch('/api/preview', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ pageData, filename })
            });

            const result = await response.json();
            if (result.success) {
                window.toast.success('预览生成成功！');
                window.open(result.url, '_blank');
                // 输入对话框已经在确认按钮点击时被移除，无需再次移除
            } else {
                window.toast.error('预览生成失败：' + result.message);
            }
        } catch (error) {
            window.toast.error('预览生成失败：' + error.message);
        }
    }

    /**
     * 应用背景设置
     */
    applyBackground() {
        this.background.color = document.getElementById('bgColor').value;
        this.background.image = document.getElementById('bgImage').value;
        
        // 只应用到画布区域
        this.canvas.style.backgroundColor = this.background.color;
        if (this.background.image) {
            this.canvas.style.backgroundImage = `url(${this.background.image})`;
            this.canvas.style.backgroundSize = 'cover';
            this.canvas.style.backgroundPosition = 'center';
            this.canvas.style.backgroundRepeat = 'no-repeat';
        } else {
            this.canvas.style.backgroundImage = 'none';
            this.canvas.style.backgroundSize = 'initial';
            this.canvas.style.backgroundPosition = 'initial';
            this.canvas.style.backgroundRepeat = 'initial';
        }
        
        document.getElementById('backgroundModal').style.display = 'none';
        window.toast.success('背景设置已应用到画布');
    }

    /**
     * 从数据应用背景
     * @param {Object} backgroundData - 背景数据
     */
    applyBackgroundFromData(backgroundData) {
        if (backgroundData.type === 'color') {
            this.canvas.style.background = backgroundData.color;
        } else if (backgroundData.type === 'image' && backgroundData.image) {
            this.canvas.style.background = `url(${backgroundData.image}) center/cover no-repeat`;
        }
    }

    /**
     * 获取画布背景信息
     * @returns {Object} 背景信息
     */
    getCanvasBackground() {
        const background = this.canvas.style.background;
        
        if (background.includes('url(')) {
            const imageMatch = background.match(/url\(['"]?([^'"]+)['"]?\)/);
            return {
                type: 'image',
                image: imageMatch ? imageMatch[1] : ''
            };
        } else if (background && background !== 'rgba(0, 0, 0, 0)') {
            return {
                type: 'color',
                color: background
            };
        }
        
        return null;
    }

    /**
     * 获取当前页面数据
     * @returns {Object} 页面数据
     */
    getPageData() {
        return {
            elements: this.elementManager.getElements(),
            background: this.getCanvasBackground(),
            timestamp: Date.now()
        };
    }
}

// 导出类（如果使用模块系统）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = PageBuilder;
}
